import { roleApi } from "@/api/role";
import { Card, CardContent } from "@/components/ui/card";
import { useEffect, useState } from "react";
import { type Role } from "@/types/role";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { sessionApi } from "@/api/session";
import { useConversationStore } from "@/store/useConversationStore";

function App() {
  const [roles, setRoles] = useState<Role[]>([]);
  const { setSelectedId, addConversation } = useConversationStore();

  useEffect(() => {
    roleApi
      .getRoleList()
      .then((res) => {
        setRoles(res.data);
      })
      .finally(() => {
        console.log(roles, "roles");
      });
  }, []);

  const handleCardClick = async (role: Role) => {
    if (role.id) {
      const { data } = await sessionApi.createChat(role.id);
      console.log(data, "role");
      const { SessionId, Role } = data;
      setSelectedId(SessionId);
      addConversation({
        id: SessionId,
        roleName: Role.name,
        roleAvatarUrl: Role.avatar_url,
        roleId: Role.id,
      });
    }
  };

  return (
    <div className="flex flex-wrap gap-4 justify-center p-4">
      {roles.map((role) => (
        <Card
          className="flex-1 min-w-[250px] max-w-sm cursor-pointer transition hover:shadow-lg"
          key={role.id}
          onClick={() => handleCardClick(role)}
        >
          <CardContent className="flex flex-col items-center p-4">
            <Avatar className="w-16 h-16 mb-2">
              <AvatarImage src={role.avatar_url} alt={role.name} />
              <AvatarFallback className="bg-black text-white">
                CN
              </AvatarFallback>
            </Avatar>
            <p className="text-lg font-medium">{role.name}</p>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

export default App;
